package com.tssup.fesco.common.queue;

import com.tssup.fesco.common.cache.Cache;
import com.tssup.fesco.common.cache.JSONSerializer;
import com.tssup.fesco.common.cache.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static java.util.Optional.ofNullable;

/**
 * Created by haomin on 2017/3/29.
 */
@Component
public class RedisQueueImpl implements IQueue {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final Long INVALID_STATUS = -1L;

    private static final Long SUCCESS_STATUS = 1L;

    private Serializer serializer = new JSONSerializer();

    @Autowired
    Cache jedis;

    @Override
    public boolean ifExist(String name) {
        try{
            return jedis.exists(name);
        }catch ( Exception e ){
            logger.error("Error happened while checking queue {} exists", name, e);
            new QueueException(e.getMessage(), e);
        }
        return false;
    }

    @Override
    public boolean ifEmpty(String name){
        try{
            if(jedis.lLen(name).compareTo(0L) > 0){
                return false;
            }else{
                return true;
            }
        }catch ( Exception e ){
            logger.error("Error happened while checking queue {} empty", name, e);
            return false;
        }
    }

    @Override
    public boolean sendMessage(String name, QueueMessage message) throws QueueException {
       try {
           Long status = ofNullable(jedis.rpush(name, serializer.serialize(message))).orElse(INVALID_STATUS);
           if(SUCCESS_STATUS.compareTo(status) == 0){
               return true;
           }else{
               return false;
           }
       }catch ( Exception e ){
           logger.error("Error happened while checking queue {} empty", name, e);
           new QueueException(e.getMessage(), e);
       }
       return false;
    }

    @Override
    public QueueMessage receive(String name) throws QueueException {
        try {
            if(!ifEmpty(name)){
                Optional message = Optional.ofNullable(jedis.lpop(name));
                if(message.isPresent()){
                    return (QueueMessage) serializer.deSerialize(message.get().toString(), QueueMessage.class);
                }else{
                    return null;
                }
            }
        }catch ( Exception e ){
            logger.error("Error happened while checking queue {} empty", name, e);
            new QueueException(e.getMessage(), e);
        }
        return null;
    }
}
